package com.starbaba.loanUnionLoginStat.service.impl;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.core.web.page.PageRequest;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.loanUnionLoginStat.model.LoanUnionLoginStatModel;
import com.starbaba.loanUnionLoginStat.model.UnionLoginConditionModel;
import com.starbaba.loanUnionLoginStat.service.LoanUnionLoginStatService;
import com.starbaba.model.dictionary.Constant;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoanUnionLoginStatServieImpl implements LoanUnionLoginStatService {
	
	@SuppressWarnings("deprecation")
	private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
	private final String productSql="select prdid as product_id,name as product_name from comm_product_prdid";
	private final String channelSql="select channel_code as channel_id,channel_name from comm_product_channel";
	private final String activityTypeSql="select activity_type as activityType_id,activity_type_name as activityType_name from register_recommend_activity";
	private final String new_activitySql="select activity as new_activity_id,remark as new_activity_name from activity_channel_config";
	private final String sourceSql="select id as source_id,name as source_name from loan_product_info where union_type!=0";
	
	//展示页面并准备数据
	@Override
	public void showPage(Map<String, Object> paramsMap) {
		try {
			//产品
			List<UnionLoginConditionModel> productList = dao.list(productSql, UnionLoginConditionModel.class);
			//渠道
			List<UnionLoginConditionModel> channelList = dao.list(channelSql, UnionLoginConditionModel.class);
			//活动类型
			List<UnionLoginConditionModel> activityTypeList = dao.list(activityTypeSql, UnionLoginConditionModel.class);
			//活动id
			List<UnionLoginConditionModel> new_activityList = dao.list(new_activitySql, UnionLoginConditionModel.class);
			//活动
			List<UnionLoginConditionModel> sourceList = dao.list(sourceSql, UnionLoginConditionModel.class);

			//显示的时候活动名称加上活动id
			if(null != sourceList){
				for (UnionLoginConditionModel source: sourceList) {
					source.setSource_name(source.getSource_name() +"(" + source.getSource_id() +")");
				}
			}
			
			paramsMap.put("productList", productList);
			paramsMap.put("channelList", channelList);
			paramsMap.put("activityTypeList", activityTypeList);
			paramsMap.put("new_activityList", new_activityList);
			paramsMap.put("sourceList", sourceList);	
			
		} catch (AppException e) {
			LogService.error("联登统计页面准备数据查询失败", e);
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<LoanUnionLoginStatModel> getStatList(PageRequest request, PageResponse response,
			Map<String, Object> paramsMap) throws Exception {
		
		int start = request.getIDisplayStart();
		int length = request.getIDisplayLength();
		
		String groupchannel = (String) paramsMap.get("groupchannel");
		
		boolean noGroupChannel = StringUtils.isBlank(groupchannel);
		
		StringBuilder sql_before =new StringBuilder();
		StringBuilder sql_after =new StringBuilder();
		
		sql_before.append("(SELECT DATE(ctime) as datetime,source_id,type,product_id,channel as channel_id,platform,order_from as loginType,new_activity_id,activity_type,environment,userType,page,ck_module,position,COUNT(DISTINCT mobnum) as loginNum,COUNT(DISTINCT mobnum,type) as jFNum");
		sql_before.append(" FROM loan_api_record  WHERE 1=1");
		//添加条件
		addCondition(sql_before, paramsMap);
		sql_before.append(" GROUP BY datetime");
		//是否需要通过channel分组
		if(!noGroupChannel){ //渠道分组
			sql_before.append(" ,channel ");
		}
		sql_before.append(" ) a LEFT JOIN ");
		
		sql_after.append("(SELECT DATE(ctime) as datetime,channel as channel_id,COUNT(DISTINCT mobnum) as loginSuccessNum,COUNT(DISTINCT mobnum,type) as jFSuccessNum");
		sql_after.append(" FROM loan_api_record  WHERE result=1 and first_union=1");
		//添加条件
		addCondition(sql_after, paramsMap);
		sql_after.append(" GROUP BY datetime ");
		if(!noGroupChannel){
			sql_after.append(" ,channel ");
		}
		sql_after.append(") b");
		
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT a.*,b.loginSuccessNum,b.jFSuccessNum FROM ");
		sql.append(sql_before.toString());
		sql.append(sql_after.toString());
		sql.append(" ON a.datetime=b.datetime ");
		if(!noGroupChannel){
			sql.append(" and a.channel_id=b.channel_id");
		}
		sql.append(" ORDER BY datetime DESC ");
		if(sql.length()>0&&start>=0&&length>0){
			sql.append(" LIMIT " + start + ", " + length);
		}
		
		StringBuilder sqlCount=new StringBuilder();
		sqlCount.append("SELECT DATE(ctime) AS datetime FROM loan_api_record WHERE 1=1 ");
		addCondition(sqlCount, paramsMap);
		sqlCount.append(" GROUP BY datetime");
		if(!noGroupChannel){
			sqlCount.append(" ,channel ");
		}
		
		int count = dao.getInt("select count(1) from ("+sqlCount.toString()+") z");
		
		List<LoanUnionLoginStatModel> list = dao.list(sql.toString(), LoanUnionLoginStatModel.class);
		
		List<LoanUnionLoginStatModel> list_show = setConditionIdToName(list, paramsMap);
		
		response.setITotalRecords(count);
		response.setITotalDisplayRecords(count);
				
		return list_show;
	}

	
	public void addCondition(StringBuilder sql,Map<String, Object> paramsMap){
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String platfrom = (String) paramsMap.get("platfrom");
		String product = (String) paramsMap.get("product");
		String channel = (String) paramsMap.get("channel");
		String activityType = (String) paramsMap.get("activityType");
		String new_activity = (String) paramsMap.get("new_activity");
		String environment = (String) paramsMap.get("environment");
		String page = (String) paramsMap.get("page");
		String ck_module = (String) paramsMap.get("ck_module");
		String position = (String) paramsMap.get("position");
		String source = (String) paramsMap.get("source");
		String loginType = (String) paramsMap.get("loginType");
		String userType = (String) paramsMap.get("userType");
		String type = (String) paramsMap.get("type");  //联登序号
		
		if(!StringUtils.isEmpty(startTime)){
			sql.append(" and ctime>='"+startTime+" 00:00:00'");
		}
		if(!StringUtils.isEmpty(endTime)){
			sql.append(" and ctime<='"+endTime+" 23:59:59'");
		}
		if(!StringUtils.isEmpty(platfrom)){
			sql.append(" and platform='"+platfrom+"'");
		}
		if(!StringUtils.isEmpty(product)){
			sql.append(" and product_id="+product+"");
		}
		if(!StringUtils.isEmpty(channel)){
			sql.append(" and channel="+channel+"");
		}
		if(!StringUtils.isEmpty(activityType)){
			sql.append(" and activity_type="+activityType+"");
		}
		if(!StringUtils.isEmpty(new_activity)){
			sql.append(" and new_activity_id="+new_activity+"");
		}
		if(!StringUtils.isEmpty(environment)){
			sql.append(" and environment="+environment+"");
		}
		if(!StringUtils.isEmpty(page)){
			sql.append(" and page="+page+"");
		}
		if(!StringUtils.isEmpty(ck_module)){
			sql.append(" and ck_module="+ck_module+"");
		}
		if(!StringUtils.isEmpty(position)){
			sql.append(" and position="+position+"");
		}
		if(!StringUtils.isEmpty(source)){
			sql.append(" and source_id="+source+"");
		}
		if(!StringUtils.isBlank(loginType)){
			if("boluodai".equalsIgnoreCase(loginType)){ //选的菠萝贷联登，查询去除熊花花的数据
				sql.append(" and (order_from != '4' or order_from is null) ");
			}else{
				sql.append(" and order_from='"+loginType+"'");
			}
		}
		if(!StringUtils.isEmpty(userType)){
			sql.append(" and userType="+userType+"");
		}

		if(StringUtils.isNotBlank(type)){
			sql.append(" and type="+type+"");
		}
	}
	
	/**
	 * 替换对象id为对应id的值
	 * @param list
	 * @return
	 * @throws AppException 
	 */
	public List<LoanUnionLoginStatModel> setConditionIdToName( List<LoanUnionLoginStatModel> list,Map<String, Object> paramsMap) throws AppException{
		
		String product = (String) paramsMap.get("product");
		String channel = (String) paramsMap.get("channel");
		String activityType = (String) paramsMap.get("activityType");
		String new_activity = (String) paramsMap.get("new_activity");
		String source = (String) paramsMap.get("source");
		String platfrom = (String) paramsMap.get("platfrom");
		String environment = (String) paramsMap.get("environment");
		String userType = (String) paramsMap.get("userType");
		String ck_module = (String) paramsMap.get("ck_module");
		String position = (String) paramsMap.get("position");
		String loginType = (String) paramsMap.get("loginType");
		String page = (String) paramsMap.get("page");
		String groupchannel = (String) paramsMap.get("groupchannel");
		String type = (String) paramsMap.get("type");
		
		//产品
		List<UnionLoginConditionModel> productList = dao.list(productSql, UnionLoginConditionModel.class);
		//渠道
		List<UnionLoginConditionModel> channelList = dao.list(channelSql, UnionLoginConditionModel.class);
		//活动类型
		List<UnionLoginConditionModel> activityTypeList = dao.list(activityTypeSql, UnionLoginConditionModel.class);
		//活动id
		List<UnionLoginConditionModel> new_activityList = dao.list(new_activitySql, UnionLoginConditionModel.class);
		//活动
		List<UnionLoginConditionModel> sourceList = dao.list(sourceSql, UnionLoginConditionModel.class);
		
		Map<String, String> productMap = getMapByList(productList);
		Map<String, String> channelMap = getMapByList(channelList);
		Map<String, String> activityTypeMap = getMapByList(activityTypeList);
		Map<String, String> new_activityMap = getMapByList(new_activityList);
		Map<String, String> sourceMap = getMapByList(sourceList);
		
		for (LoanUnionLoginStatModel bean : list) {
			
			if(StringUtils.isBlank(product)){
				bean.setProduct_id("全部");
			}else{
				bean.setProduct_id(productMap.get(product));
			}
			
			if(StringUtils.isBlank(channel)&&StringUtils.isBlank(groupchannel)){
				bean.setChannel_id("全部");
			}else{
				String channel_id = bean.getChannel_id();
				bean.setChannel_id(channelMap.get(channel_id));
			}
			
			if(StringUtils.isBlank(activityType)){
				bean.setActivity_type("全部");
			}else{
				bean.setActivity_type(activityTypeMap.get(activityType));
			}
			
			if(StringUtils.isBlank(new_activity)){
				bean.setNew_activity_id("全部");
			}else{
				bean.setNew_activity_id(new_activityMap.get(new_activity));
			}
			
			if(StringUtils.isBlank(source)){
				bean.setSource_id("全部");
			}else{
				bean.setSource_id(sourceMap.get(source));
			}

			if(StringUtils.isBlank(type)){
				bean.setType("全部");
			}
			
			if(StringUtils.isBlank(platfrom)){
				bean.setPlatform("全部");
			}
			
			if(StringUtils.isBlank(environment)){
				bean.setEnvironment("全部");
			}
			
			if(StringUtils.isBlank(userType)){
				bean.setUserType("全部");
			}
			
			if(StringUtils.isBlank(ck_module)){
				bean.setCk_module("全部");
			}
			
			if(StringUtils.isBlank(position)){
				bean.setPosition("全部");
			}
			
			if(StringUtils.isBlank(loginType)){
				bean.setLoginType("全部");
			}
			
			if(StringUtils.isBlank(page)){
				bean.setPage("全部");
			}
			
		}
		
		return list;	
	}
	
	/**
	 * 把list里面的值拆分为key ,value返回map
	 * @param list
	 * @return
	 */
	public Map<String,String> getMapByList(List<UnionLoginConditionModel> list){
		Map<String, String> map = new HashMap<String,String>();
		
		for (UnionLoginConditionModel bean : list) {
			String product_id = bean.getProduct_id();
			String product_name = bean.getProduct_name();
			
			String channel_id = bean.getChannel_id();
			String channel_name = bean.getChannel_name();
			
			String activityType_id = bean.getActivityType_id();
			String activityType_name = bean.getActivityType_name();
			
			String new_activity_id = bean.getNew_activity_id();
			String new_activity_name = bean.getNew_activity_name();
			
			String source_id = bean.getSource_id();
			String source_name = bean.getSource_name();
			
			if(!StringUtils.isBlank(product_id)){
				map.put(product_id,product_name);
			}
			if(!StringUtils.isBlank(channel_id)){
				map.put(channel_id,channel_name);
			}
			if(!StringUtils.isBlank(activityType_id)){
				map.put(activityType_id,activityType_name);
			}
			if(!StringUtils.isBlank(new_activity_id)){
				map.put(new_activity_id,new_activity_name);
			}
			if(!StringUtils.isBlank(source_id)){
				map.put(source_id,source_name);
			}
		}
		
		return map;
	}

	@Override
	public String exportDetailCVS(List<LoanUnionLoginStatModel> loanUnionLoginStatModel) {
		StringBuffer detail = new StringBuffer();
		detail.append("日期,产品,平台,渠道,活动类型,活动ID,环境,用户,页面,模块,位置,活动,联登序号,联登类型,请求联登人数,联登成功人数,请求联登甲方,联登成功甲方\r\n");
		for (LoanUnionLoginStatModel list : loanUnionLoginStatModel) {
			detail.append(list.getDatetime()).append(",");
			detail.append(list.getProduct_id()).append(",");
			detail.append(list.getPlatform()).append(",");
			detail.append(list.getChannel_id()).append(",");
			detail.append(list.getActivity_type()).append(",");
			detail.append(list.getNew_activity_id()).append(",");
			
			String environment = list.getEnvironment();
			if("1".equals(environment)){
				detail.append("推广H5").append(",");
			}else if("2".equals(environment)){
				detail.append("客户端").append(",");
			}
			
			String userType = list.getUserType();
			if("0".equals(userType)){
				detail.append("老用户").append(",");
			}else if("1".equals(userType)){
				detail.append("新用户").append(",");
			}
			
			detail.append(list.getPage()).append(",");
			detail.append(list.getCk_module()).append(",");
			detail.append(list.getPosition()).append(",");
			detail.append(list.getSource_id()).append(",");
			detail.append(list.getType()).append(",");
			
			String loginType = list.getLoginType();
			if("1".equals(loginType)){
				detail.append("一键联登").append(",");	
			}else if("2".equals(loginType)){
				detail.append("普通联登").append(",");
			}
			
			
			detail.append(list.getLoginNum()).append(",");
			detail.append(list.getLoginSuccessNum()).append(",");
			detail.append(list.getjFNum()).append(",");
			detail.append(list.getjFSuccessNum()).append(",");
			detail.append("\r\n");
		}
		return detail.toString();
	}
}
